package cn.iocoder.yudao.module.system.config.transcoder;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.module.system.config.tools.FFmpegTools;
import cn.iocoder.yudao.module.system.dal.dataobject.a_audio_and_video.AudioAndVideoDO;
import cn.iocoder.yudao.module.system.dal.mysql.a_audio_and_video.AudioAndVideoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * 视频转码
 */
@Component
@Slf4j
public class Transcoder {

    /**
     * 上传文件存储在本地的根路径 - 视频
     */
    @Value("${fileData.videoPath}")
    private String FILE_VIDEO;

    @Resource
    private AudioAndVideoMapper audioAndVideoMapper;

    @Resource
    FFmpegTools ffmpegTools;

    @Async("transcoderTaskExecutor")
    public void run(AudioAndVideoDO audioAndVideoDO) {
        log.info("转码任务开始执行 -->" + Thread.currentThread().getName() + " time:" + System.currentTimeMillis());
        String path = audioAndVideoDO.getAbsolutePath();
        String ext = audioAndVideoDO.getType() == 0 ? "m3u8" : "mp3";
        String output = FileUtil.getParent(path, 1) + "/" + FileUtil.getPrefix(path) + "." + ext;
        Boolean success = audioAndVideoDO.getType() == 0
                ? ffmpegTools.convertToHLS(path, 10L, output)
                : ffmpegTools.transcodeMP3(path, 128, output);
        if (success) {
            audioAndVideoDO.setTranscoderUrl(audioAndVideoDO.getUrl().replace(FileUtil.getSuffix(path), ext));
            audioAndVideoDO.setTranscoderStatus(10);
        } else {
            audioAndVideoDO.setTranscoderStatus(-1);
        }
        audioAndVideoMapper.save(audioAndVideoDO);
        log.info("转码任务开始结束 -->" + Thread.currentThread().getName() + " time:" + System.currentTimeMillis());
    }

}
